package com.bothin.experiment4.security;

import com.bothin.experiment4.model.Employee;
import com.bothin.experiment4.security.LoginUser;
import com.bothin.experiment4.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by bothin
 * At 2019/12/22 0:27
 * Description:
 */
@Service
public class LoginUserServiceImpl implements UserDetailsService {
    @Autowired
    private IEmployeeService employeeService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Employee employee = employeeService.findByAccount(s);
        return buildUserDetails(employee);
    }

    /**
     * 创建用户
     * @param user
     * @return
     */
    private UserDetails buildUserDetails(Employee user) {
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("ROLE_" + user.getRole().toUpperCase()));
        LoginUser loginUser = new LoginUser();
        loginUser.setEmployeeId(user.getEmployeeId());
        loginUser.setUsername(user.getAccount());
        loginUser.setPassword(user.getPassword());
        loginUser.setAuthorities(list);

        return loginUser;
    }
}
